package com.cw.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.common.api.Response;
import com.cw.common.constant.Constants;
import com.cw.common.method.CommonMethod;
import com.cw.common.method.SendCardMsg;
import com.cw.dto.InpatientRegistrationCondition;
import com.cw.entity.*;
import com.cw.mapper2.*;
import com.cw.service.IPatientBedMiddleService;
import com.cw.service.IThisIaNurseVsDeptService;
import com.cw.util.HttpUtil;
import com.cw.util.MQMsg;
import com.cw.util.StringUtil;
import com.cw.util.UUIDUtil;
import com.cw.vo.spdVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author smq
 * @since 2021-05-09
 */
@Service
//@Transactional(rollbackFor = Exception.class, timeout = 5)
public class PatientBedMiddleServiceImpl extends ServiceImpl<PatientBedMiddleMapper, PatientBedMiddle> implements IPatientBedMiddleService {

    @Autowired
    private ApplicationBedMapper applicationBedMapper;

    @Autowired
    private MqLogMapper mqLogMapper;

    @Autowired
    private HisCwglNurseMapper hisCwglNurseMapper;

    @Autowired
    private REmployeeMapper rEmployeeMapper;

    @Autowired
    private WeChatLogMapper weChatLogMapper;

    @Autowired
    private TelMessageMapper telMessageMapper;

    @Autowired
    private PatientBedMiddleMapper patientBedMiddleMapper;

    @Autowired
    private ExtInformationMapper extInformationMapper;

    @Autowired
    private ThisIiPrepayinMapper thisIiPrepayinMapper;

    @Autowired
    private HisCwglBedMapper hisCwglBedMapper;

    @Autowired
    private ThisIiInmaininfoMapper thisIiInmaininfoMapper;


    private static ReentrantLock lock = new ReentrantLock();

    private MQMsg mqMsg = new MQMsg();

//    private MsgInfo msgInfo = new MsgInfo();

    private CommonMethod commonMethod = new CommonMethod();

    private SendCardMsg sendCardMsg = new SendCardMsg();


    /**
     * 中间表关联预约表 查询已登记列表的数据
     *
     * @param condition 查询条件
     * @return com.github.pagehelper.PageInfo<com.cw.entity.PatientBedMiddle>
     * @author ly
     * @date 2021/5/9 16:32
     */
    @Override
    public List<ThisIiInmaininfo> getPatientBedMiddle(InpatientRegistrationCondition condition) {
        List<ThisIiInmaininfo> thisIiPrepayins;

        String code = condition.getCode();
        PageInfo<ThisIiInmaininfo> thisIiInmaininfoPageInfo = null;
        //急诊
        if ("2".equals(code)) {
            Integer nullPointCheck = condition.getEmergencyCallPageNum();
            if (ObjectUtil.isNotNull(nullPointCheck)) {
                PageHelper.startPage(nullPointCheck, 21);
                thisIiPrepayins = baseMapper.getThisIiInmaininfos(condition);
                thisIiInmaininfoPageInfo = new PageInfo<>(thisIiPrepayins);
            }
        }

        //门诊查询
        if ("1".equals(code)) {
            Integer nullPoint = condition.getOutpatientPageNum();
            if (ObjectUtil.isNotNull(nullPoint)) {
                PageHelper.startPage(nullPoint, 21);
                thisIiPrepayins = baseMapper.getThisIiInmaininfos(condition);
                thisIiInmaininfoPageInfo = new PageInfo<>(thisIiPrepayins);
            }
        }

        assert thisIiInmaininfoPageInfo != null;
        return thisIiInmaininfoPageInfo.getList();
    }


    public Response determineSPD(String nurseCellCode, String roomNo) {
        if (StringUtil.isEmpty(nurseCellCode) || StringUtil.isEmpty(roomNo)) {
            return new Response(500, "病区号/房间号不能为空");
        }
        List<spdVO> spdVOS = thisIiInmaininfoMapper.determineSPD(nurseCellCode, roomNo);
        if (CollectionUtils.isNotEmpty(spdVOS)) {
            return new Response(200, "", true);
        } else {
            return new Response(200, "", false);
        }
    }

    /**
     * 床位登记
     *
     * @param bedId
     * @param patientId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response addPatientBed(String bedId, String patientId) {
        lock.lock();
        try {
            //判断是否被预约
            List<PatientBedMiddle> patientBedNew = baseMapper.selectList(new LambdaQueryWrapper<>(new PatientBedMiddle()).eq(PatientBedMiddle::getBedNo, bedId).eq(PatientBedMiddle::getState, "1"));
            if (CollectionUtils.isNotEmpty(patientBedNew)) {
                return new Response(500, "床位预约失败,该床已被占用");
            }
            //判断预约患者者是否 0取消预约2转入院3出院9作废
            //获取患者信息
            ThisIiPrepayin thisIiPrepayin = thisIiPrepayinMapper.selectById(patientId);
            if ("0".equals(thisIiPrepayin.getPreState())) {
                return new Response(500, "床位预约失败，该患者电子住院证已取消");
            } else if ("1".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者已预约床位");
            } else if ("2".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者已入院");
            } else if ("3".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者已出院");
            } else if ("9".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者电子住院证已作废");
            }
            //根据床位编码获取床位信息
            HisCwglBed hisCwglBed = hisCwglBedMapper.selectList(new LambdaQueryWrapper<>(new HisCwglBed()).eq(HisCwglBed::getBedNo, bedId)).get(0);
            String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
            String userId = HttpUtil.getRequestHeaderInfo(Constants.USER_ID);
            //根据病人PreId获取病人信息
            ThisIiPrepayin patientInfo = thisIiPrepayinMapper.selectById(patientId);
            //根据病人PreId获取电子一体化床位申请信息
            ApplicationBed applicationBed = applicationBedMapper.selectById(patientId);
            PatientBedMiddle patientBed = new PatientBedMiddle();
            patientBed.setId(UUIDUtil.uuid());
            patientBed.setBedNo(bedId);
            patientBed.setIdenno(thisIiPrepayin.getIdenno());
            patientBed.setPreid(thisIiPrepayin.getPreid());
            //床位视图中查询的，根据床位号可以查询到该床属于哪个院区
            String yard = hisCwglBed.getYard();
            //特殊处理，如果是浒关院区，那么短信应该发给开立医生，而不是取jobNumber，但是这里入参就可以判断处理，不需要改后面方法
            if ("2".equals(yard)) {
                applicationBed.setJobNumber(thisIiPrepayin.getOperCode());
            }
            patientBed.setYard(yard);
            patientBed.setNurseCellCode(hisCwglBed.getNurseCellCode());
            patientBed.setNurseCellName(hisCwglBed.getNurseCellName());
            patientBed.setNurseCellCodeBefore(thisIiPrepayin.getNurseCellCode());
            patientBed.setDeptCode(hisCwglBed.getDeptCode());
            patientBed.setDeptName(hisCwglBed.getDeptName());
            patientBed.setState("1");//已预约
            patientBed.setOperNo(userId);
            patientBed.setOpenName(userName);
            patientBed.setOperTime(LocalDateTime.now());
            //如果电子住院证中有住院号,将住院号回写至预约表(先去住院处登记的情况)
            patientBed.setInpatientNo(patientInfo.getInpatientNo());
            Integer insert = baseMapper.insert(patientBed);
            //修改预约表信息
            // 预约状态 0 未预约   1已预约
            thisIiPrepayin.setRegisteStatus("1");
            thisIiPrepayin.setNurseCellCode(hisCwglBed.getNurseCellCode());
            thisIiPrepayin.setBedNo(hisCwglBed.getBedNo());
            List<BigDecimal> peridLst = new ArrayList<>();
            peridLst.add(thisIiPrepayin.getPreid());
            Integer update = thisIiPrepayinMapper.updateById(thisIiPrepayin);
            //系统内预约目前不发短信消息
            if (applicationBed == null) {
                return new Response(200, "床位预约成功");
            }
            if (insert > 0 && update > 0) {
                applicationBedMapper.UpdateBatchApplicationStatus(peridLst, null, "1");
                sendMsg(applicationBed, patientInfo, userId, userName, hisCwglBed, 0, "");

            } else {
                return new Response(500, "床位预约失败");
            }

        } catch (Exception e) {
            return new Response(500, "床位预约失败");
        } finally {
            lock.unlock();
        }
        return new Response(200, "床位预约成功");

    }


    /**
     * 转床
     *
     * @param bedId
     * @param patientId
     * @return
     */
    @Override
    public Response changePatientBed1(String bedId, String patientId, String deptCode, String deptName, String sdeptCode) {
        lock.lock();
        try {
            String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
            String userId = HttpUtil.getRequestHeaderInfo(Constants.USER_ID);

            List<String> bedStates = new ArrayList<>();
            bedStates.add("1");
//			bedStates.add("2");
//			bedStates.add("3");
            //获取该用户原来床位信息
            List<PatientBedMiddle> patientBedList = baseMapper.selectList(new LambdaQueryWrapper<>(new PatientBedMiddle()).eq(PatientBedMiddle::getPreid, patientId).in(PatientBedMiddle::getState, bedStates));
            if (CollectionUtils.isEmpty(patientBedList) || patientBedList.size() != 1) {
                return new Response(500, "转床失败");
            }
            //判断是否被预约
            List<PatientBedMiddle> parameters = baseMapper.selectList(new LambdaQueryWrapper<>(new PatientBedMiddle()).eq(PatientBedMiddle::getBedNo, bedId).in(PatientBedMiddle::getState, bedStates));
            if (CollectionUtils.isNotEmpty(parameters)) {
                return new Response(500, "转床失败，该床位已被占用");
            }
            PatientBedMiddle patientBed = patientBedList.get(0);
            if (!"1".equals(patientBed.getState())) {
                return new Response(500, "转床失败,该用户不能转床");
            }
            //根据床位编码获取新的床位信息
            HisCwglBed hisCwglBed = hisCwglBedMapper.selectList(new LambdaQueryWrapper<>(new HisCwglBed()).eq(HisCwglBed::getBedNo, bedId)).get(0);
            //修改原来预约的信息
            patientBed.setBedNo(bedId);
            patientBed.setYard(hisCwglBed.getYard());
            patientBed.setNurseCellCode(hisCwglBed.getNurseCellCode());
            patientBed.setNurseCellName(hisCwglBed.getNurseCellName());
            patientBed.setDeptCode(hisCwglBed.getDeptCode());
            patientBed.setDeptName(hisCwglBed.getDeptName());
            //已预约
            patientBed.setState("1");
            patientBed.setOperNo(userId);
            patientBed.setOpenName(userName);
            patientBed.setOperTime(LocalDateTime.now());
            Integer update = baseMapper.updateById(patientBed);

            //判断登记患者者是否 0取消预约2转入院3出院9作废
            //获取患者信息
            ThisIiPrepayin thisIiPrepayin = thisIiPrepayinMapper.selectById(patientId);
            if ("0".equals(thisIiPrepayin.getPreState()) || "2".equals(thisIiPrepayin.getPreState()) || "3".equals(thisIiPrepayin.getPreState()) || "9".equals(thisIiPrepayin.getPreState())) {
                return new Response(500, "转床失败，该患者没有预约权限");
            }
            //修改预约表信息
            // 预约状态 0 未预约   1已预约
            thisIiPrepayin.setRegisteStatus("1");
//            thisIiPrepayin.setPreState("1");
            thisIiPrepayin.setNurseCellCode(hisCwglBed.getNurseCellCode());
            thisIiPrepayin.setBedNo(hisCwglBed.getBedNo());
            thisIiPrepayin.setDeptCode(deptCode);
            thisIiPrepayin.setDeptName(deptName);
            thisIiPrepayin.setSdeptCode(sdeptCode);
            Integer update1 = thisIiPrepayinMapper.updateById(thisIiPrepayin);

            if (update > 0 && update1 > 0) {
                return new Response(200, "转床成功");
            } else {
                return new Response(500, "转床失败");
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * 取消预约
     *
     * @param bedId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response delPatientBed(String bedId, String patientId, String remark) {
        try {
            ThisIiPrepayin patientInfo = thisIiPrepayinMapper.selectById(patientId);
            HisCwglBed hisCwglBed = hisCwglBedMapper.selectList(new LambdaQueryWrapper<>(new HisCwglBed()).eq(HisCwglBed::getBedNo, bedId)).get(0);
            //根据病人PreId获取电子一体化床位申请信息
            ApplicationBed applicationBed = applicationBedMapper.selectById(patientId);
            String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
            String userId = HttpUtil.getRequestHeaderInfo(Constants.USER_ID);
            String realName = HttpUtil.getRequestHeaderInfo("realname");
            //更改状态为取消登记 4 取消登记
            //根据床位id和患者id获取中间表信息
            List<PatientBedMiddle> patientBedMiddles = baseMapper.selectList(new LambdaQueryWrapper<>(new PatientBedMiddle()).eq(PatientBedMiddle::getBedNo, bedId).eq(PatientBedMiddle::getPreid, patientId).eq(PatientBedMiddle::getState, "1"));
            if (CollectionUtils.isEmpty(patientBedMiddles) || patientBedMiddles.size() != 1) {
                return new Response(500, "取消失败，该患者没有已预约的床位");
            }
            PatientBedMiddle patientBedMiddle = patientBedMiddles.get(0);
            //修改状态
            patientBedMiddle.setState("4");
            patientBedMiddle.setOperNo(userId);
            patientBedMiddle.setOpenName(userName);
            patientBedMiddle.setOperTime(LocalDateTime.now());//修改时间 cww 06-22
            Integer del = baseMapper.updateById(patientBedMiddle);
            //获取该患者预约表信息
            ThisIiPrepayin thisIiPrepayin = thisIiPrepayinMapper.selectById(patientId);
            //修改预约表状态
            thisIiPrepayin.setRegisteStatus("0");
            thisIiPrepayin.setBedNo("");
            thisIiPrepayin.setNurseCellCode(patientBedMiddle.getNurseCellCodeBefore());
            Integer update = thisIiPrepayinMapper.updateById(thisIiPrepayin);
            List<BigDecimal> peridLst = new ArrayList<>();
            peridLst.add(thisIiPrepayin.getPreid());
            // 如果这个地方不是从医惠床位申请页面过来的请求就直接返回
            if (applicationBed == null) {
                return new Response(200, "取消成功");
            }
            if (update > 0 && del > 0) {
                applicationBedMapper.UpdateBatchApplicationStatus(peridLst, null, "0");
                sendMsg(applicationBed, patientInfo, userId, userName, hisCwglBed, 1, remark);
            } else {
                return new Response(500, "取消失败");
            }
        } catch (Exception ex) {
            int a=0;
        }
        return new Response(200, "取消成功");
    }


    /**
     * 根据床位ids已预约床位
     *
     * @param bedIds
     * @return
     */
    @Override
    public List<PatientBedMiddle> getRegisterBedByBedIds(List<String> bedIds) {
//	  List<PatientBedMiddle> patientBedMiddles = new ArrayList<>();
        List<String> status = new ArrayList<>();
        status.add("1");
//	  preStates.add("2");
        status.add("4");
        status.add("5");
        List<PatientBedMiddle> patientBedMiddles = baseMapper.getRegisterBedByBedIds(bedIds, status);
//	  return baseMapper.selectList(new LambdaQueryWrapper<>(new PatientBedMiddle()).in(PatientBedMiddle::getBedNo, bedIds)
//														 .eq(PatientBedMiddle::getDeleteFlag, "0"));
        return patientBedMiddles;
    }

    @Override
    public List<PatientBedMiddle> getAllRegisterBeds() {
        return baseMapper.getRegisterBedByBedIds(null, null);
    }


    /**
     * 获取已预约却又超过一小时没登记的患者信息
     *
     * @return java.util.List<java.lang.String>
     * @author ly
     * @date 2021/5/25 15:54
     */
    @Override
    public List<String> getAppointmentTimeOut() {
        LocalDateTime nowTime = LocalDateTime.now();
        //减去一小时
        nowTime = nowTime.minusHours(1);

        List<ThisIiPrepayin> appointmentTimeOut = baseMapper.getAppointmentTimeOut(nowTime);
        if (CollectionUtils.isEmpty(appointmentTimeOut)) {
            return null;
        }

        return appointmentTimeOut.stream().filter(thisIiPrepayin -> {
            String builder = thisIiPrepayin.getName() + "预约的" + thisIiPrepayin.getDeptName() + thisIiPrepayin.getNurseCellName() + thisIiPrepayin.getBedNo() + "号床登记时间已经超过1小时,请及时处理!";
            thisIiPrepayin.setWorkTel(builder);
            return true;
        }).map(ThisIiPrepayin::getWorkTel).collect(Collectors.toList());
    }

    @Override
    //一键释放
    @Transactional(rollbackFor = Exception.class)
    public Response updateReleaseBed() {
        Date currDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ExtInformation> insertList = new ArrayList<>();
        //拿到middle表里已预约的人
        List<PatientBedMiddle> alreadyAppointmentList = patientBedMiddleMapper.getReserved();
        if (!alreadyAppointmentList.isEmpty()) {
            List<BigDecimal> preidList = alreadyAppointmentList.stream().map(t -> t.getPreid()).collect(Collectors.toList());
            patientBedMiddleMapper.updateReleaseBed(preidList);
            thisIiPrepayinMapper.updateBedNo(preidList);
            //根据Preid去查这些患者信息
            List<PatientBedMiddle> patientBedMiddles = patientBedMiddleMapper.selectPreidBed(preidList);
            //List<BigDecimal> getAllPatientsList = patientBedMiddles.stream().map(t -> t.getPreid()).collect(Collectors.toList());
            patientBedMiddles.forEach(item -> {
                ExtInformation entity = new ExtInformation();
                //消息类型
                entity.setMessageTpye("AutomaticRelease");
                entity.setExtendField1(item.getPreid() != null ? String.valueOf(item.getPreid()) : ""); //PreID
                entity.setExtendField2(item.getInpatientNo() != null ? item.getInpatientNo() : ""); //住院证号
                entity.setExtendField3(item.getNurseCellCode() != null ? item.getNurseCellCode() : "");//病区编号
                entity.setExtendField4(item.getNurseCellName() != null ? item.getNurseCellName() : "");//病区名称
                entity.setExtendField5(item.getDeptCode() != null ? item.getDeptCode() : "");   //科室代码
                entity.setExtendField6(item.getDeptName() != null ? item.getDeptName() : "");   //科室名称
                String bedNo = item.getBedNo() == null ? "" : commonMethod.getBedName(item.getBedNo() != null ? String.valueOf(item.getBedNo()) : "");
                entity.setExtendField7(bedNo);      //床位号
                entity.setExtendField8("");
                entity.setExtendField9("");
                //创建人
                String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
                entity.setCreatedBy(userName);
                //创建时间
                entity.setCreatedTime(sdf.format(currDate));
                //字段备注
                entity.setMessageTypeRemark("ExtendField1为PreIdExtendField2为患者住院号ExtendField3为病区代码ExtendField4为病区名称ExtendField5为科室代码ExtendField6为科室名称ExtendField7为床位号");
                insertList.add(entity);
            });
            //对EXT_INFORMATION进行插表操作
            extInformationMapper.addNonHeaderCalibration(insertList);

        } else if (alreadyAppointmentList.isEmpty()) {
            return Response.error("没有要释放的床位");
        }
        return Response.success("释放成功");
    }

    //测试回滚的 记得删除
    @Override
    @Transactional
    public void addExtTest(ExtInformation entity) {
        entity.setMessageTpye("回滚事务");
        Date currDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:hh:ss");
        entity.setCreatedTime(sdf.format(currDate));
        String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
        userName = userName == null || userName.isEmpty() ? "徐宁达测试" : userName;
        entity.setCreatedBy(userName);
        entity.setMessageTypeRemark("测试数据");
        extInformationMapper.addTestTranstional(entity);
        int i = 1;
        int s = 0;
        int a = i / s;
    }

    @Override
    public Response getCacelReson() {
        return Response.success(baseMapper.getCacelReson());
    }

    public void setMsg(MsgInfo msgInfo) {
        ApplicationBed applicationBed = applicationBedMapper.selectById(msgInfo.getPreid());
        if (applicationBed != null) {
            // 设定用户
            mqMsg.setUserName("S01");
            // 设定密码
            mqMsg.setPassword("123456");
            // 设定通道池
            mqMsg.setQueueManagerName("QMGR.P01");
            // 设定消息频道
            mqMsg.setChannel("PS35035");

            mqMsg.setPatName(msgInfo.getName());                // 设定姓名
            mqMsg.setPatIndexNo(msgInfo.getPreid().toString()); // 索引号
            mqMsg.setMsgTitle(msgInfo.getTitle());
//            mqMsg.setMsgTitle("测试数据！！！请忽略！！！");
            //发给个人
            mqMsg.setMessageType("2");


            // 设定消息内容
            mqMsg.setMsgContent("患者:" + msgInfo.getName() + "(" + msgInfo.getDeptName() + ") " + msgInfo.getResult() + msgInfo.getYardName() + "院区-" + msgInfo.getNurseCellName() + msgInfo.getBedNum() + "床位");
            mqMsg.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            mqMsg.setSenderCode(msgInfo.getEmplCode());        // 设定发送者工号
            mqMsg.setSenderName(msgInfo.getEmplName());        // 设定发送者姓名
            mqMsg.setBedNum(msgInfo.getBedNum());        // 设定床位号
            mqMsg.setDeptCode(msgInfo.getDeptCode());    // 设定科室编号
            mqMsg.setDeptName(msgInfo.getDeptName());    // 设定科室名称
            mqMsg.setWardCode(msgInfo.getNurseCellCode());    // 病区代码
            // 设定病区名称
            mqMsg.setWardName(msgInfo.getNurseCellName());
            // 设定院区编号
            mqMsg.setHospDistrictCode(msgInfo.getYard());
            // 设定院区
            mqMsg.setHostDistrictName(msgInfo.getYardName());
//		mqMsg.setOIInd(patientInfo.getConsultationCode());		// 设定门诊住院标识
            mqMsg.setReciveCode(applicationBed.getJobNumber());
            mqMsg.setReciveName(applicationBed.getCreateBy());
            String xmlString = mqMsg.createXMLString(mqMsg);

            MqLog mqLog = new MqLog();
            String uuid = UUIDUtil.uuid();
            mqLog.setId(uuid);
            mqLog.setRequestMsg(xmlString);
            mqLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            mqLog.setSenderCode(msgInfo.getEmplCode());
            mqLog.setSenderName(msgInfo.getEmplName());

            String msgId = mqMsg.putMsg(xmlString);
            System.out.println(msgId);
            mqLog.setMsgId(msgId);
            if (msgId != "") {
                mqLog.setResponseType("success");
            } else {
                mqLog.setResponseType("fail");
            }
            mqLogMapper.insert(mqLog);
        }
    }

    public void setDeptMsg(MsgInfo msgInfo) {
        ApplicationBed applicationBed = applicationBedMapper.selectById(msgInfo.getPreid());
        if (applicationBed != null) {
            // 设定用户
            mqMsg.setUserName("S01");
            // 设定密码
            mqMsg.setPassword("123456");
            // 设定通道池
            mqMsg.setQueueManagerName("QMGR.P01");
            // 设定消息频道
            mqMsg.setChannel("PS35035");

            mqMsg.setPatName(msgInfo.getName());                // 设定姓名
            mqMsg.setPatIndexNo(msgInfo.getPreid().toString()); // 索引号
            mqMsg.setMsgTitle(msgInfo.getTitle());
//            mqMsg.setMsgTitle("测试数据！请忽略！！！");
            //发给部门
            mqMsg.setMessageType("1");


            // 设定消息内容
            mqMsg.setMsgContent("患者:" + msgInfo.getName() + "(" + msgInfo.getDeptName() + ") " + msgInfo.getResult() + msgInfo.getYardName() + "院区-" + msgInfo.getNurseCellName() + msgInfo.getBedNum() + "床位");
            mqMsg.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            mqMsg.setSenderCode(msgInfo.getEmplCode());        // 设定发送者工号
            mqMsg.setSenderName(msgInfo.getEmplName());        // 设定发送者姓名
            mqMsg.setBedNum(msgInfo.getBedNum());        // 设定床位号
            mqMsg.setDeptCode("");    // 设定科室编号
            mqMsg.setDeptName("");    // 设定科室名称
            mqMsg.setWardCode(msgInfo.getNurseCellCode());    // 病区代码
            mqMsg.setWardName(msgInfo.getNurseCellName());   // 设定病区名称
            mqMsg.setHospDistrictCode(msgInfo.getYard());      // 设定院区编号
            mqMsg.setHostDistrictName(msgInfo.getYardName());  // 设定院区
//		mqMsg.setOIInd(patientInfo.getConsultationCode());		// 设定门诊住院标识
//            mqMsg.setReciveCode(applicationBed.getJobNumber());
//            mqMsg.setReciveName(applicationBed.getCreateBy());
            String xmlString = mqMsg.createXMLString(mqMsg);

            MqLog mqLog = new MqLog();
            String uuid = UUIDUtil.uuid();
            mqLog.setId(uuid);
            mqLog.setRequestMsg(xmlString);
            mqLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            mqLog.setSenderCode(msgInfo.getEmplCode());
            mqLog.setSenderName(msgInfo.getEmplName());

            String msgId = mqMsg.putMsg(xmlString);
            System.out.println(msgId);
            mqLog.setMsgId(msgId);
            if (msgId != "") {
                mqLog.setResponseType("success");
            } else {
                mqLog.setResponseType("fail");
            }
            mqLogMapper.insert(mqLog);
        }
    }

    public MsgInfo getMsgInfo(ApplicationBed applicationBed, ThisIiPrepayin patientInfo, String userid, String userName, HisCwglBed hisCwglBed, String remark, Integer flag) {
        MsgInfo info = new MsgInfo();
        info.setEmplCode(applicationBed.getJobNumber());
        info.setEmplName(applicationBed.getCreateBy());
        info.setUserId(userid);
        info.setUserName(userName);
        info.setYard(hisCwglBed.getYard());
        if (StringUtil.isEmpty(remark)) {
            info.setRemark("入住时间/入住病区/房间号未达患者预期。");
        } else {
            info.setRemark(remark);
        }
        if ("2".equals(hisCwglBed.getYard())) {
            info.setYardName("浒关");
        } else {
            info.setYardName("三香");
        }
        if (flag == 1) {
            info.setTitle("取消床位成功");
            info.setResult("已取消");
        } else {
            info.setTitle("预约床位成功");
            info.setResult("已预约");
        }
        if (patientInfo != null) {
            info.setPreid(patientInfo.getPreid());
            info.setName(patientInfo.getName());
            info.setDeptCode(patientInfo.getDeptCode());
            info.setDeptName(patientInfo.getDeptName());
            info.setBedNum(commonMethod.getBedName(patientInfo.getBedNo()));
            //在外面判断了，这里就不判断了
//            if (patientInfo.getHomeTel() == null){
//                info.setLinkmanTel(patientInfo.getLinkmanTel());
//            } else{
//                info.setLinkmanTel(patientInfo.getHomeTel());
//            }

            info.setLinkmanTel(patientInfo.getHomeTel());
            LambdaQueryWrapper<HisCwglNurse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(HisCwglNurse::getDeptCode, patientInfo.getNurseCellCode()).eq(HisCwglNurse::getYard, hisCwglBed.getYard());

            HisCwglNurse hisCwglNurse = hisCwglNurseMapper.selectOne(lambdaQueryWrapper);
            info.setNurseCellCode(patientInfo.getNurseCellCode());    // 病区代码
            info.setNurseCellName(hisCwglNurse.getDeptName());

            LambdaQueryWrapper<REmployee> lambdaQueryEmployeeWrapper = new LambdaQueryWrapper<>();
            lambdaQueryEmployeeWrapper.eq(REmployee::getEmplCode, applicationBed.getJobNumber());
            REmployee retREmployee = rEmployeeMapper.selectOne(lambdaQueryEmployeeWrapper);
            if (retREmployee != null) {
                info.setWechatAccountCode(retREmployee.getXgzh());
            }
        }
        return info;
    }

    /**
     * @param applicationBed 申请床位对象
     * @param patientInfo    患者信息
     * @param userId         用户id
     * @param userName       用户名
     * @param hisCwglBed     床位信息
     * @param flag           1:取消床位 0:预约床位
     * @param remark         取消原因 只有取消预约时有值
     */
    private void sendMsg(ApplicationBed applicationBed, ThisIiPrepayin patientInfo, String userId, String userName, HisCwglBed hisCwglBed, Integer flag, String remark) {
        /**
         * modify by cww at 2024-08-27 短信发送联系电话和联系人
         * 通常为两个信息第一个为患者本人信息,第二个为联系人信息
         * 也有可能有一条或没有
         */
        List<MsgInfo> lstMsgInfo = new ArrayList<>();
        if (StringUtil.isNotEmpty(patientInfo.getHomeTel())) {
            MsgInfo msgInfo = getMsgInfo(applicationBed, patientInfo, userId, userName, hisCwglBed, remark, flag);
            lstMsgInfo.add(msgInfo);
        }
        if (StringUtil.isNotEmpty(patientInfo.getLinkmanTel())) {
            patientInfo.setHomeTel(patientInfo.getLinkmanTel());
            MsgInfo msgInfo = getMsgInfo(applicationBed, patientInfo, userId, userName, hisCwglBed, remark, flag);
            lstMsgInfo.add(msgInfo);
        }
        new Thread(() -> {
            try {
                //发送MQ   （这个是发给个人的）
                if (CollectionUtils.isNotEmpty(lstMsgInfo)) {
                    MsgInfo msgInfo = lstMsgInfo.get(0);
                    setMsg(msgInfo);
                    //再发一次  （这个是发给科室|病区的）
                    setDeptMsg(msgInfo);
                    //发送企业微信
                    if (msgInfo.getWechatAccountCode() != null && !msgInfo.getWechatAccountCode().isEmpty()) {
                        //企业微信返回josn消息体
                        //调用post发送企业微信消息
                        WeChatLog weChatLog = SendCardMsg.send2(msgInfo);
                        weChatLogMapper.insert(weChatLog);
                        //调用医院发送手机短信的接口,这里要发送给患者本人和联系人
                        for (int i = 0; i < lstMsgInfo.size(); i++) {
                            MsgInfo telMsgInfo = lstMsgInfo.get(i);
                            TelMessageLog telMessageLog = SendCardMsg.sendTelMessage(telMsgInfo, flag);
                            telMessageMapper.insert(telMessageLog);
                        }

                    }
                }

            } catch (Exception ex) {
                int a = 0;
            }
        }).start();
    }
}
